<?php
namespace app\apijson\query\operators;

class GroupOperator
{
    public static function applyGroup($query, $value)
    {
        $groups = explode(',', $value);
        $safeGroups = [];
        foreach ($groups as $group) {
            $group = trim($group);
            if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*]*$/', $group)) {
                throw new \app\apijson\core\ApiJsonException('非法分组字段: ' . $group);
            }
            $safeGroups[] = $group;
        }
        $query->groupBy($safeGroups);
    }

    public static function applyHaving($query, $value)
    {
        // 支持 HAVING 子句，格式：字段名 操作符 值
        // 例如：@having: "count(*) > 10" 或 "sum(amount) >= 1000"
        if (is_string($value)) {
            // 验证 HAVING 条件的安全性
            if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*()\s]+(>=|<=|>|<|=|!=)\s*[0-9.]+$/', trim($value))) {
                throw new \app\apijson\core\ApiJsonException('非法的 HAVING 条件格式: ' . $value);
            }
            $query->havingRaw($value);
        } elseif (is_array($value)) {
            // 支持数组格式：['field', 'operator', 'value']
            foreach ($value as $havingItem) {
                if (is_array($havingItem) && count($havingItem) >= 3) {
                    [$field, $operator, $havingValue] = $havingItem;
                    // 验证字段名和操作符
                    if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*()]*$/', $field)) {
                        throw new \app\apijson\core\ApiJsonException('非法的 HAVING 字段: ' . $field);
                    }
                    if (!in_array($operator, ['>=', '<=', '>', '<', '=', '!='])) {
                        throw new \app\apijson\core\ApiJsonException('非法的 HAVING 操作符: ' . $operator);
                    }
                    $query->having($field, $operator, $havingValue);
                }
            }
        }
    }
} 